#include <stdio.h>
#include <string.h>

/*
 * S -> BA
 * A -> BS|d
 * B -> aA|bS|c
 * BA => aAA => aBSA => abSSA => abBASA => abcASA => abcdBAA => abcdcAA => abcdcdA => abcdcdd
 */
int current;
char buffer[1024];

int S();
int A();
int B();

int match(char x) {
	if(buffer[current] == x) {
		current ++;
		return 1;
	} else {
		return 0;
	}
}

int S() {
	return B() && A();
}

int A() {
	switch(buffer[current]) {
		case 'a':
		case 'b':
		case 'c':
			return B() && S();
		case 'd':
			return match('d');
		default:
			return 0;
	}
}

// B -> aA|bS|c
int B() {
	switch(buffer[current]) {
		case 'a':
			return match('a') && A();
		case 'b':
			return match('b') && S();
		case 'c':
			return match('c');
		default:
			return 0;
	}
}

int main() {
	strcpy(buffer, "abcdcdd");
	current = 0;
	if(S()) {
		printf("matched\n");
	} else {
		printf("unmatched\n");
	}
	return 0;
}

